﻿using Core.Utility;
using System;
using System.ComponentModel;
using System.IO;

namespace Core.Config
{
    [Serializable]
    public class ConfigDat
    {
        #region Field
        protected string path = string.Empty;
        #endregion

        #region Constructor
        public ConfigDat() { }
        #endregion

        #region Property
        /// <summary>
        /// 文件夹名
        /// </summary>
        [Browsable(false)]
        public string Folder { get { return folder; } set { folder = value; } }
        protected string folder = "DefaultFolder";
        /// <summary>
        /// 文件名
        /// </summary>
        [Browsable(false)]
        public string FileName { get { return fileName; } set { fileName = value; } }
        protected string fileName = string.Empty;
        #endregion

        #region Method
        /// <summary>
        /// 保存
        /// </summary>
        /// <returns>true=保存成功，false=保存失败</returns>
        public virtual bool Save()
        {
            try
            {
                path = string.Format(@"{0}\Config\{1}\{2}.Dat", Environment.CurrentDirectory, folder, string.IsNullOrEmpty(fileName) ? this.GetType().Name : fileName);
                return AccessDatSerializer.ObjectToDat(path, this);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message, ex);
            }
        }

        /// <summary>
        /// 读取
        /// </summary>
        /// <returns>读取结果</returns>
        public virtual object Read()
        {
            path = string.Format(@"{0}\Config\{1}\{2}.dat", Environment.CurrentDirectory, folder, string.IsNullOrEmpty(fileName) ? this.GetType().Name : fileName);
            try
            {
                if (File.Exists(path))
                {
                    return AccessDatSerializer.DatToObject(path);
                }
                else
                {
                    if (Save())
                    {
                        //NotifyG.Add(this.Name + "读取配置文件不存在,系统将自动创建一份默认配置文件：成功");
                    }
                    return AccessDatSerializer.DatToObject(path);
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message,ex);
            }
        }

        /// <summary>
        ///读取
        /// </summary>
        /// <typeparam fileName="T">读取类型</typeparam>
        /// <returns>读取成功，返回结果数据。读取失败，引用类型会返回null，数值类型会返回零</returns>
        public T Read<T>()
        {
            try
            {
                return (T)Read();
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message, ex);
            }
        }
        #endregion

    }
}
